﻿
Partial Class WebForm_ManageWorkContent_AddPlanHeader
    Inherits System.Web.UI.UserControl

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        Me.fv.EditItemTemplate = Me.fv.InsertItemTemplate
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then

        End If

        ScriptManager.GetCurrent(Me.Page).RegisterPostBackControl(Me.fv.FindControl("btnSave"))
        ScriptManager.GetCurrent(Me.Page).RegisterPostBackControl(Me.fv.FindControl("lbtnFileName"))
    End Sub

    Protected Sub SearchEmployeeControl1_SelectedIndexChanged(ByVal source As Object, ByVal e As System.EventArgs) Handles SearchEmployeeControl1.SelectedIndexChanged
        TryCast(Me.fv.FindControl("txtOrganizationName"), TextBox).Text = Me.SearchEmployeeControl1.OrganizationName
        TryCast(Me.fv.FindControl("txtPersonInCharge"), TextBox).Text = Me.SearchEmployeeControl1.UserName
        Me.UOrganizationID = Me.SearchEmployeeControl1.UOrganizationID
    End Sub

    Protected Sub fv_ItemCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewCommandEventArgs) Handles fv.ItemCommand
        If e.CommandName = "Select" Then
            Me.SearchEmployeeControl1.Show()
        ElseIf e.CommandName = "Download" Then

            Dim FileInfo As New System.IO.FileInfo(Server.MapPath(e.CommandArgument.ToString()))
            Me.Response.Clear()
            Me.Response.AddHeader("Content-Disposition", ("attachment;filename=" & Server.UrlPathEncode(CType(Me.fv.FindControl("lbtnFileName"), LinkButton).Text)))
            Me.Response.HeaderEncoding = System.Text.Encoding.GetEncoding("utf-8")
            Me.Response.AddHeader("Content-Length", FileInfo.Length.ToString())
            Me.Response.ContentType = "application/octet-stream"
            Me.Response.WriteFile(FileInfo.FullName)

            Me.Response.End()
        ElseIf e.CommandName = "Save" Then
            If Me.Save() Then
                RaiseEvent Saved(Me, New EventArgs)
            Else
                MyObj.ShowMessage("新增失敗")
            End If
        End If
    End Sub

    Protected Sub fv_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles fv.DataBound
        If Me.fv.CurrentMode = FormViewMode.Edit Then
            Me.UOrganizationID = DataBinder.Eval(Me.fv.DataItem, "OrganizationID").ToString()
        End If
    End Sub
End Class

Partial Class WebForm_ManageWorkContent_AddPlanHeader

#Region "初始化資料"
    Public Sub InitData()
        Me.fv.ChangeMode(FormViewMode.Insert)
        Me.fv.DataBind()
    End Sub

    Public Sub InitData(ByVal planheaderID As String)
        Me.fv.ChangeMode(FormViewMode.Edit)
        'Me.fv.ChangeMode(Me.DataAccessMode)
        Me.PlanHeaderID = planheaderID
        Me.BindData()
    End Sub

    Private Sub BindData()
        Dim dat As New clsData
        Dim sql As New MyStringBuilder
        Dim dt As Data.DataTable

        sql.AppendFormat(" select a.*,b.OrganizationName  ")
        sql.AppendFormat(" from CleanPlanHeader a inner join OrganizationView b ")
        sql.AppendFormat(" on a.OrganizationID = b.UOrganizationID ")
        sql.AppendFormat(" where 1=1 ")
        sql.AppendFormat(" and a.PlanHeaderID = {0} ", Me.PlanHeaderID)

        dt = dat.GetData(sql)

        Me.fv.DataSource = dt
        Me.fv.DataBind()
    End Sub

#End Region


#Region "儲存"
    Protected Function Save() As Boolean

        Dim dat As New clsData
        Dim sql As New MyStringBuilder

        If Me.fv.CurrentMode = FormViewMode.Insert Then

            '新增前先檢查 單位+年度 是否已有計畫(每年度只能有一個計畫)
            sql.Length = 0
            sql.AppendFormat(" Select * From CleanPlanHeader ")
            sql.AppendFormat(" Where Year = '{0}' ", CType(Me.fv.FindControl("AnnualControl1"), WebForm_CommonControl_AnnualControl).Anaual)
            sql.AppendFormat(" And OrganizationID='{0}' ", Me.UOrganizationID)

            'sql.AddWithValue("Year", CType(Me.fv.FindControl("AnnualControl1"), WebForm_CommonControl_AnnualControl).Anaual)
            'sql.AddWithValue("OrganizationID", Me.UOrganizationID)

            If dat.GetData(sql).Rows.Count > 0 Then
                MyObj.ShowMessage("此單位的年度計畫已存在")
                Return False
            End If

            '檢查是否有上傳檔案
            If Not CType(Me.fv.FindControl("FileUpload1"), FileUpload).HasFile Then
                MyObj.ShowMessage("請選擇欲上傳的年度計畫檔案")
                Return False
            End If

            '將檔案存至Server
            Dim fileName As String = CType(Me.fv.FindControl("FileUpload1"), FileUpload).FileName
            Dim guidFileSaveName As String = Guid.NewGuid().ToString() + "." + fileName.Substring(fileName.LastIndexOf(".") + 1)
            Dim FileSaveUrl As String = "~/Downloads/ClanPlanHeader/" + guidFileSaveName.ToString()
            CType(Me.fv.FindControl("FileUpload1"), FileUpload).SaveAs(Server.MapPath(FileSaveUrl))

            sql.Length = 0

            sql.AppendFormat(" Insert Into CleanPlanHeader([Year],OrganizationID,PersonInCharge,[Subject],[FileName],FileUrl,CreateBy,CreateDate,UpdateBy,UpdateDate) ")
            sql.AppendFormat(" select ")
            sql.AppendFormat("'{0}', ", CType(Me.fv.FindControl("AnnualControl1"), WebForm_CommonControl_AnnualControl).Anaual)
            sql.AppendFormat("'{0}', ", Me.UOrganizationID)
            sql.AppendFormat("'{0}', ", Me.fv.FindTxtControl("txtPersonInCharge").Text)
            sql.AppendFormat("'{0}', ", "")
            sql.AppendFormat("'{0}', ", CType(Me.fv.FindControl("FileUpload1"), FileUpload).FileName)
            sql.AppendFormat("'{0}', ", FileSaveUrl)
            sql.AppendFormat("'{0}', ", clsAuth.GetUserID())
            sql.AppendFormat("{0}, ", "getdate()")
            sql.AppendFormat("'{0}', ", clsAuth.GetUserID())
            sql.AppendFormat("{0} ", "getdate()")
            Try
                dat.AccData(sql)

            Catch ex As Exception
                Return False
            End Try

        ElseIf Me.fv.CurrentMode = FormViewMode.Edit Then

            '更新前先檢查 單位+年度(自己本身不算) 是否已有計畫(每年度只能有一個計畫)
            sql.Length = 0
            sql.AppendFormat(" Select * From( ")
            sql.AppendFormat(" Select Year,OrganizationID from CleanPlanHeader ")
            sql.AppendFormat(" Where Year+','+OrganizationID <> ")
            sql.AppendFormat(" (Select Year+','+OrganizationID From CleanPlanHeader Where PlanHeaderID={0}) ", Me.PlanHeaderID)
            sql.AppendFormat(" ) T ")
            sql.AppendFormat(" Where Year = '{0}' And OrganizationID='{1}' ", CType(Me.fv.FindControl("AnnualControl1"), WebForm_CommonControl_AnnualControl).Anaual, Me.UOrganizationID)

            'sql.AddWithValue("Year", CType(Me.fv.FindControl("AnnualControl1"), WebForm_CommonControl_AnnualControl).Anaual)
            'sql.AddWithValue("OrganizationID", Me.UOrganizationID)
            'sql.AddWithValue("PlanHeaderID", Me.PlanHeaderID)

            If dat.GetData(sql).Rows.Count > 0 Then
                MyObj.ShowMessage("此單位的年度計畫已存在")
                Return False
            End If

            sql.Length = 0

            sql.AppendFormat(" Update CleanPlanHeader  ")
            sql.AppendFormat(" Set UpdateBy = '{0}' ", clsAuth.GetUserID())
            sql.AppendFormat(" ,[Year]='{0}' ", CType(Me.fv.FindControl("AnnualControl1"), WebForm_CommonControl_AnnualControl).Anaual)
            sql.AppendFormat(" ,OrganizationID='{0}' ", Me.UOrganizationID)
            sql.AppendFormat(" ,PersonInCharge='{0}' ", Me.fv.FindTxtControl("txtPersonInCharge").Text)

            '若需更新檔案
            If CType(Me.fv.FindControl("FileUpload1"), FileUpload).HasFile Then
                '更新前先將舊檔刪除
                System.IO.File.Delete(Server.MapPath(CType(Me.fv.FindControl("lbtnFileName"), LinkButton).CommandArgument.ToString()))

                Dim fileName As String = CType(Me.fv.FindControl("FileUpload1"), FileUpload).FileName
                Dim guidFileSaveName As String = Guid.NewGuid().ToString() + "." + fileName.Substring(fileName.LastIndexOf(".") + 1)
                Dim FileSaveUrl As String = "~/Downloads/ClanPlanHeader/" + guidFileSaveName.ToString()

                sql.AppendFormat(" ,[FileName] = '{0}' ", CType(Me.fv.FindControl("FileUpload1"), FileUpload).FileName)
                sql.AppendFormat(" ,FileUrl='{0}' ", FileSaveUrl)

                'sql.AddWithValue("FileName", CType(Me.fv.FindControl("FileUpload1"), FileUpload).FileName)
                'sql.AddWithValue("FileUrl", FileSaveUrl)

                '將檔案上傳至Server
                CType(Me.fv.FindControl("FileUpload1"), FileUpload).SaveAs(Server.MapPath(FileSaveUrl))
            End If

            sql.AppendFormat(" ,UpdateDate = getDate() ")
            sql.AppendFormat(" where PlanHeaderID = {0} ", Me.PlanHeaderID)

            'sql.AddWithValue("PersonInCharge", Me.fv.FindTxtControl("txtPersonInCharge").Text)
            'sql.AddWithValue("UpdateBy", clsAuth.GetUserID())


            Try
                dat.AccData(sql)
            Catch ex As Exception
                Return False
            End Try

        End If

        Return True

    End Function
#End Region

#Region "事件"
    Public Event Saved(ByVal source As Object, ByVal e As EventArgs)
#End Region

#Region "屬性"

    Public Property OriginalUOrganizationID() As String
        Get
            Return ViewState("OriginalUOrganizationID")
        End Get
        Set(ByVal value As String)
            ViewState("OriginalUOrganizationID") = value
        End Set
    End Property

    Public Property UOrganizationID() As String
        Get
            Return ViewState("UOrganizationID")
        End Get
        Set(ByVal value As String)
            ViewState("UOrganizationID") = value
        End Set
    End Property

    Public Property PlanHeaderID() As String
        Get
            Return ViewState("PlanHeaderID")
        End Get
        Set(ByVal value As String)
            ViewState("PlanHeaderID") = value
        End Set
    End Property

#End Region
End Class
